package com.huoshan.im.server.action;

import com.huoshan.im.server.ContextNaming;
import com.huoshan.im.server.SessionHolder;
import com.huoshan.im.server.action.support.JsonActionSupport;
import com.huoshan.im.server.config.ConfigHolder;
import com.huoshan.im.server.dto.in.SvrLoginMessage;
import com.huoshan.im.server.messaging.MessageId;
import com.qy.esports.common.utils.JsonUtils;
import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import online.chazi.bootplus.commons.utils.JwtUtils;
import online.chazi.netkit.annotation.Inject;
import org.springframework.util.ObjectUtils;

import java.net.InetSocketAddress;

/**
 * 说明: 用于repeater与server连接登录
 */
@Slf4j
@Inject
public class SysLoginAction extends JsonActionSupport<SvrLoginMessage> {

    public void execute(SvrLoginMessage message) {

        log.info("系统登录, message: {}", JsonUtils.toJson(message));

        if (ObjectUtils.isEmpty(message) || ObjectUtils.isEmpty(message.getTo火山九日())) {
            sendMessageAndClose(MessageId.SRV_LOGIN_FAIL);
        }

        try {

            Claims claims = JwtUtils.parseJwt(message.getTo火山九日(), ConfigHolder.getSettingConfig().getSysKey());
            log.debug("登录成功~~~");
            //保存用户信息
            setAttribute(ContextNaming.SESSION_SYSTEM_ID, claims.getId());
//            SessionHolder.addSystemSession(Integer.parseInt(claims.getAudience()), getSession());
            //登录成功。
            sendMessage(MessageId.SRV_LOGIN_SUCCESS);

            // 获取repeater客户端IP - 以repeater上报的注册到nacos上的ip为准
            InetSocketAddress remote = (InetSocketAddress) getSession().getRemoteAddress();
            String ip = ObjectUtils.isEmpty(message.getIp()) ? remote.getAddress().getHostAddress() : message.getIp();
            String repeaterId = String.format("%s:%s", ip, message.getPort());
            log.info("系统登录, ip: {}, port: {}", ip, message.getPort());

            // 绑定repeater客户端session
            setAttribute(ContextNaming.SESSION_REPEATER_ID, repeaterId);
            SessionHolder.addRepeaterSession(repeaterId, getSession());


        } catch (Exception e) {
            log.error("登录失败", e);
            sendMessageAndClose(MessageId.SRV_LOGIN_FAIL);
        }

    }

}
